package org.nettyServer.messageHandle;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.nettyServer.command.CommandBase;
import org.nettyServer.connectionManage.ClientInfo;
import org.nettyServer.connectionManage.ConnectionManage;

import java.util.Map;
import java.util.Objects;
@Slf4j
public class MessageInfoRecord {

    /**
     * 接受的有效消息记录
     * @param commandBase
     * @param channel
     * @param msg
     */
    public static void effectiveReceiveMessageInfoRecord(CommandBase commandBase, Channel channel, Object msg){
        ClientInfo clientInfo = ConnectionManage.getClientInfo(channel);

        if (Objects.isNull(clientInfo)){
            log.error("接收消息时, 该连接未登录，不进行消息记录");
            return;
        }
        //有效消息记录
        //设置数量
        ClientInfo.MessageInfo receiveInfo = clientInfo.getReceiveInfo();
        receiveInfo.setCount(receiveInfo.getCount()+1);
        //设置大小
        byte[] bytes= (byte[])msg;
        receiveInfo.setBytes(receiveInfo.getBytes()+(long) bytes.length);

        //设置具体消息的记录
        Map<String, ClientInfo.MessageInfo> map = clientInfo.getReceiveMessageInfoMap();
        map.forEach((k,v)->{
            if (k.equals(commandBase.getCommandCode())){
                v.setCount(v.getCount()+1);
                v.setBytes(v.getBytes()+(long) bytes.length);
            }
        });
    }

    public static void pushMessageInfoRecord(CommandBase commandBase, Channel channel,byte[] bytes){
        ClientInfo clientInfo = ConnectionManage.getClientInfo(channel);
        if (Objects.isNull(clientInfo)){
            log.error("发送消息时, 该连接未登录，不进行消息记录");
            return;
        }
        clientInfo.getSendInfo().setCount(clientInfo.getSendInfo().getCount()+1);
        clientInfo.getSendInfo().setBytes(clientInfo.getSendInfo().getBytes()+(long) bytes.length);

        //设置具体消息的记录
        Map<String, ClientInfo.MessageInfo> map = clientInfo.getSendMessageInfoMap();
        map.forEach((k,v)->{
            if (k.equals(commandBase.getCommandCode())){
                v.setCount(v.getCount()+1);
                v.setBytes(v.getBytes()+(long) bytes.length);
            }
        });
    }

}
